<?php
declare (strict_types = 1);

namespace app\admin\controller;

use think\facade\Session;
use app\common\controller\Admin;
use think\Request;

class Order extends Admin
{
    protected $with = ['order_detailed'=>['specification_sku','product'=>['product_image']],'user_index','address'=>['z','c'],'log'=>['user']];
    public function initialize()
    {
        $this->menu_input = [
            'all' => [
            ],
            'add' => [
            ],
            'upload' => [
            ],
        ];
        parent::initialize(); // TODO: Change the autogenerated stub
    }
    public function table_mage(&$data = [])
    {
        $data = [
            ['field' => 'create_time', 'title' => '下单时间'],
            ['field' => 'xz', 'title' => '所属乡镇'],
            ['field' => 'product_name', 'title' => '产品'],
                ['field' => 'sh_name', 'title' => '收货人'],
            ['field' => 'y_price', 'title' => '订单金额（元）'],
            ['field' => 'cb_price', 'title' => '订单成本价（元）'],
            ['field' => 'lr_price', 'title' => '订单利润（元）'],
            ['field' => 'status', 'title' => '订单状态'],
            ['title' => '操作', 'templet' => '#list_setting']
        ];
        if(input('status') == 4){
            $data = [
                ['field' => 'create_time', 'title' => '下单时间'],
                ['field' => 'xz', 'title' => '所属乡镇'],
                ['field' => 'product_name', 'title' => '产品'],
                ['field' => 'sh_name', 'title' => '收货人'],
                ['field' => 'y_price', 'title' => '订单金额（元）'],
                ['field' => 'cb_price', 'title' => '订单成本价（元）'],
                ['field' => 'lr_price', 'title' => '订单利润（元）'],
                ['field' => 'status', 'title' => '订单状态'],
                ['title' => '操作', 'templet' => '#list_setting']
            ];
        }
        return parent::table_mage($data); // TODO: Change the autogenerated stub
    }
    public function index()
    {
    	$city = app('app\admin\model\Township')->where('parent_id','<>',0)->select()->toArray();
    	$login = Session::get('login');
    	if($login['usergroup'][0]['group_id'] == 6){
    		$this->assign('user',$login);
    		//当前账号为配送员账号,只能查看绑定的乡的订单
    		if(input('status') == 2){
        		$this->assign('ps',1);
    		}else{
        		$this->assign('ps',2);
    		}
    	}
    	
    	$login = Session::get('login');
    	if($login['usergroup'][0]['group_id'] == 6){
    	    $data = [];
    		//当前账号为配送员账号,只能查看绑定的乡的订单
    		$tow = app('app\admin\model\UserTow')->where('user_id','=',$login['id'])->select();
    		$id = '';
    		if(!empty($tow) && !empty($tow->toArray())){
    		    $tow = $tow->toArray();
    		    foreach ($tow as $k=>$v){
    		        foreach ($city as $kk=>$vv)
            		{
            		    if($v['township_id'] == $vv['id']){
            		        $data[] = ['id'=>$vv['id'],'name'=>$vv['name']];
            		    }
            		}
    		    }
        		
    		}
    		$this->assign('tow',$data);
    	}
        $this->assign('city',$city);
    	if(input('status') && input('status') == 4){
    		$this->assign('status',4);
    	}
        return parent::index(); // TODO: Change the autogenerated stub
    }
    //列表-数据接口
    public function datalist()
    {
        if (is_array($this->with)) {
            $with = $this->with;
        } else {
            $with = [];
        }
        $data = param();
        unset($data['page']);
        unset($data['limit']);
        unset($data['parent']);
        foreach ($data as $k => $v) {
            if (in_array($k, ['name', 'title'])) {
                $this->where[] = [$k, 'like', '%' . $v . '%'];
            } elseif ($k == 'create_time') {
                $arr = b_arr($v, '-');
                $first = b_str([$arr[0], $arr[1], $arr[2]], '-');
                $last = b_str([$arr[3], $arr[4], $arr[5]], '-');
                $this->where[] = ['create_time', '>=', trim($first)];
                $this->where[] = ['create_time', '<=', trim($last)];
            } else {
                $this->where[] = [$k, 'like', '%' . $v . '%'];
            }
        }
    	$login = Session::get('login');
    	if($login['usergroup'][0]['group_id'] == 6){
    		//当前账号为配送员账号,只能查看绑定的乡的订单
    		$tow = app('app\admin\model\UserTow')->where('user_id','=',$login['id'])->select();
    		$id = '';
    		if(!empty($tow) && !empty($tow->toArray())){
    		    $tow = $tow->toArray();
    		    foreach ($tow as $k=>$v)
    		    {
    		       if(empty($id)){
    		           $id = (string)$v['township_id'];
    		       }else{
    		           $id .= (','.$v['township_id']);
    		       } 
    		    }
    		    $this->where[] = ['z_id','in',$id];
    		}else{
    		    $this->where[] = ['z_id','=','-1'];
    		}
    	}
    // 	pr($this->where);
        $order = $this->order ?: 'id desc';
        $this->index_where($this->where);
        if(!empty($this->where)){
            $this->where = array_values($this->where);
        }
        // pr($this->where);
        $list = $this->model->where($this->where)->order($order)->with($with)->paginate($this->limit)->toArray();
        $this->index_handle($list);
        return layui($list['data'], $list['total']);
    }

    public function index_handle(&$data)
    {
        $data['data'] = array_map(function($v){
            if($v['status'] == 1){
                $v['status'] = '待支付';
            }elseif ($v['status'] == 2){
                $v['status'] = '待发货';
            }elseif ($v['status'] == 3){
                $v['status'] = '待收货';
            }elseif ($v['status'] == 4){
                $v['status'] = '未结算';
            }elseif ($v['status'] == 5){
                $v['status'] = '结算申请中';
            }elseif ($v['status'] == 6){
                $v['status'] = '已完成';
            }elseif ($v['status'] == 7){
                $v['status'] = '取消';
            }
            $v['sh_name'] = $v['address']['name'];
            $v['cb_price'] = 0;
            $product_name = '';
            foreach ($v['order_detailed'] as $kk=>$vv){
                $v['cb_price'] += ($vv['specification_sku']['cb_price']*$vv['num']);
                if(empty($product_name)){
                    $product_name = $vv['product']['name'];
                }else{
                    $product_name .= '/'.$vv['product']['name'];
                }
            }
            if(!empty($product_name)){
                 $product_name = mb_substr($product_name,0,10);
                if(count($v['order_detailed']) > 1){
                    $product_name .= '...等'.count($v['order_detailed']).'样商品';
                }   
            }
            
            $v['product_name'] = $product_name;
            $v['lr_price'] = ($v['y_price']*1 - $v['cb_price']);
            $c_data = app('app\admin\model\Township')->where('id',$v['z_id'])->find()->toArray();
            if($c_data['parent_id'] != 0){
                $z_data = app('app\admin\model\Township')->where('id',$c_data['parent_id'])->find();
                if(!empty($z_data) && !empty($z_data->toArray()))
                {
                    $z_data = $z_data->toArray();
                }else{
                    $z_data['name'] = '';
                }
                $v['xz'] = $z_data['name'].'-'.$c_data['name'];
            }else{
                $v['xz'] = $c_data['name'];
            }
            $v['product_name'] = $product_name;
            return $v;
        },$data['data']);

        return parent::index_handle($data); // TODO: Change the autogenerated stub
    }
    //编辑-页面
    public function upload()
    {
        $id = input('id');
        $data = $this->model->where('id',$id)->with($this->with)->find()->toArray();
        $SpecificationValue_model = app('app\admin\model\SpecificationValue');
        foreach ($data['order_detailed'] as $k=>$v){
            if(!isset($v['product']['images'])){
                $images = [];
                $data['order_detailed'][$k]['gg_name'] = '';
            }else{
                $images = explode(',',$v['product']['images']);
                $data['order_detailed'][$k]['product']['images'] = $images;
                if($v['specification_sku']['specification_value_ids'] == '0'){
                    $str = '无规格';
                }else{
                    $id = explode(',',$v['specification_sku']['specification_value_ids']);
                    $str = '';
                    foreach ($id as $vv){
                        $pz =  $SpecificationValue_model->where('id','=',$vv)->with('specification_key')->find()->toArray();
                        $str .= $pz['name'].'/';
                    }
                }
                $data['order_detailed'][$k]['gg_name'] = $str;
            }
            
        }
        $data['log_money'] = 0;
        $data['wjq_money'] = 0;
        if(!empty($data['log'])){
            //合计操作结清金额
            foreach ($data['log'] as $k=>$v){
                $data['log_money'] += $v['money'];
            }
            //未结清金额
            $data['wjq_money'] = $data['y_price']-$data['log_money'];
        }else{
            $data['wjq_money'] = $data['y_price'];
        }
        // pr($data);
        $this->assign('data',$data);
        return view();
    }
    public function index_where(&$where)
    {
        if(!empty($where) && is_array($where)){
            foreach ($where as $k=>$v){
                if($v[0] == 'time_time'){
                    $time = explode('到',$v[2]);
                    $where[] = ['create_time','>=',trim($time[0])];
                    $where[] = ['create_time','<=',trim($time[1])];
                    unset($where[$k]);
                }elseif($v[0] == 'dy'){
                    $where[] = ['status','in','4,5'];
                    unset($where[$k]);
                }elseif($v[0] == 'sh_name'){
                    //收货人
                    $Address_model = app('app\admin\model\Address');
                    $address_data = $Address_model->where('name','like','%'.$v[2].'%')->select();
                    $ids = [];
                    if(!empty($address_data) && !empty($address_data->toArray()))
                    {
                        $address_data = $address_data->toArray();
                        foreach ($address_data as $kk=>$vv)
                        {
                            $ids[] = $vv['id'];
                        }
                    }
                    if(!empty($ids)){
                        $ids = implode(',',$ids);
                        $where[] = ['address_id','in',$ids];
                    }else{
                        $where[] = ['address_id','=','-1'];
                    }
                    unset($where[$k]);
                }
            }
        }
        return parent::index_where($where); // TODO: Change the autogenerated stub
    }
}
